package app

import (
	"fmt"
	"math/rand"
	"net/http"
	"strconv"
	"sync/atomic"
	"time"
)

type gatewayInterface interface {
	Increase(w http.ResponseWriter)
	Decrease()
	LimitRequest() *pool
}

type pool struct {
	max_thread   int32
	total_thread int32
	threads      chan string
}

var Gateway gatewayInterface

func init() {
	pool := &pool{}
	pool.max_thread = 2
	pool.threads = make(chan string, pool.max_thread)
	Gateway = pool
	//Todo:超时关闭协程
}

func (this *pool) Increase(w http.ResponseWriter) {
	thread_number := fmt.Sprintf("%s%s", time.Now().Format("20060102150405"), strconv.Itoa(rand.Intn(100000)))
	atomic.AddInt32(&this.total_thread, 1)
	if atomic.LoadInt32(&this.total_thread) > this.max_thread {
		fmt.Println("达到请求上限,等待中！ 线程号:", thread_number)
	}
	//this.threads <- thread_number
	fmt.Println(" 进入请求池 线程号:", thread_number)
	fmt.Println("请求池+1 总数:", atomic.LoadInt32(&this.total_thread))
}

func (this *pool) Decrease() {
	//打开这里模拟耗时请求,用几个请求测试下
	//time.Sleep(5 * time.Second)
	atomic.AddInt32(&this.total_thread, -1)
	//thread_number := <-this.threads
	thread_number := fmt.Sprintf("%s%s", time.Now().Format("20060102150405"), strconv.Itoa(rand.Intn(100000)))
	this.threads <- thread_number
	fmt.Println("退出请求池 线程号:", thread_number)
	fmt.Println("请求池-1 总数:", this.total_thread)
}

func (this *pool) LimitRequest() *pool {
	//超出协程数
	if atomic.LoadInt32(&this.total_thread) >= this.max_thread {
		//fmt.Println("达到请求上限", this.total_thread)
		//进入等待队列或响应"服务器繁忙,请稍后再试"...
	}
	return this
}
